#include "receivefile.h"
#include <QFile>

ReceiveFile::ReceiveFile(QTcpSocket* tcp,QObject *parent)
    : QThread{parent}
{
    m_tcp = tcp;
}

void ReceiveFile::run()
{
    QFile* file = new QFile("recv.txt");
    if(file->open(QFile::WriteOnly))
{
    //接受数据
    connect(m_tcp , &QTcpSocket::readyRead , this, [=](){
        //第一次接受文件，先读文件的大小
        //添加一个静态的局部变量
        static int count = 0;
        static int total = 0;
        if (count == 0)
        {
            m_tcp->read((char*)&total, 4);
        }
        //读出剩余数据
        QByteArray all =  m_tcp->readAll();
        count += all.size();
        file->write(all);

        //判断数据是否接受完了
        if (count ==total)
        {
            m_tcp->close();
            m_tcp->deleteLater();
            file->close();
            file->deleteLater();
            emit over();
        }
    });
}
    else
        qDebug()<<"没打开";
    exec();   //调用exec函数，底层进行事件循环    子线程必须加exec
}
